import { makeAutoObservable } from 'mobx';
import { HubUserType } from '@/types/globalType';

interface UserInfo {
  username: string;
  userId: string;
  user?: any;
  [key: string]: string | number | boolean | object;
}

/**
 * 认证Store
 */
class LoginStore {
  isAuthenticated = false;
  token: string | null = null;
  userInfo: UserInfo | null = null;

  constructor() {
    makeAutoObservable(this);
    // 从本地存储中恢复登录状态
    this.init();
  }

  init() {
    this.token = localStorage.getItem('token');
    const userInfoStr = localStorage.getItem('userInfo');
    
    if (this.token && userInfoStr) {
      try {
        this.userInfo = JSON.parse(userInfoStr);
        this.setHubUser(this.userInfo);
        this.isAuthenticated = true;
      } catch (error) {
        console.error('解析用户信息失败:', error);
        this.logout();
      }
    } else {
      this.isAuthenticated = false;
    }
  }

  /**
   * 登录
   * @param token 令牌
   * @param userInfo 用户信息
   */
  login(token: string, userInfo: UserInfo) {
    this.isAuthenticated = true;
    this.token = token;
    this.userInfo = userInfo;
    this.setHubUser(userInfo);

    // 保存到本地存储
    localStorage.setItem('token', token);
    localStorage.setItem('userInfo', JSON.stringify(userInfo));
    localStorage.setItem('auth', 'true');
    this.init();
  }

  /**
   * 退出登录
   */
  logout() {
    this.isAuthenticated = false;
    this.token = null;
    this.userInfo = null;
    window.HubUser = undefined;

    // 清除本地存储
    localStorage.removeItem('token');
    localStorage.removeItem('userInfo');
    localStorage.removeItem('auth');
  }

  /**
   * 设置全局用户对象
   * @param userInfo 用户信息
   */
  setHubUser(userInfo: UserInfo) {
    if (!userInfo?.user) return;

    const hubUser: HubUserType = {
      id: userInfo.user.id,
      username: userInfo.user.username,
      name: userInfo.user.name,
      email: userInfo.user.email,
      phone: userInfo.user.phone,
      number: userInfo.user.number,
      roleId: userInfo.user.roleId,
      roleIds: userInfo.user.roleIds,
      status: userInfo.user.status,
      skin: userInfo.user.skin,
      bz: userInfo.user.bz,
      createTime: userInfo.user.createTime,
      updateTime: userInfo.user.updateTime,
      deleteType: userInfo.user.deleteType,
      role: userInfo.user.role || 'user',
      avatar: userInfo.user.avatar,
      permissions: userInfo.user.permissions || []
    };

    window.HubUser = hubUser;
  }

  /**
   *
   * @returns
   */
  getUserInfo() {
    return this.userInfo;
  }

  /**
   * 获取用户名
   * @returns 用户名
   */
  getUsername() {
    return this.userInfo?.username || '';
  }

  /**
   * 获取用户ID
   * @returns 用户ID
   */
  getUserId() {
    return this.userInfo?.userId || '';
  }
}

export const loginStore = new LoginStore();